package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/4/7 13:20
 */
public class C4 {

    // https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
    // 两个有序数组做一个归并操作. 返回新的数组
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] newArr = merge(nums1, nums2, nums1.length, nums2.length);
        int mid = newArr.length / 2;
        return newArr.length % 2 == 0 ? (newArr[mid] + newArr[mid - 1]) / 2.0 : newArr[mid];
    }

    private static int[] merge(int[] nums1, int[] nums2, int lBorder, int rBorder) {
        int l = 0, r = 0, i = 0;
        int[] newArr = new int[lBorder + rBorder];
        while (l < lBorder && r < rBorder) {
            newArr[i++] = nums1[l] <= nums2[r] ? nums1[l++] : nums2[r++];
        }
        // 两种情况: l越界或r越界
        while (l < lBorder) {
            newArr[i++] = nums1[l++];
        }
        while (r < rBorder) {
            newArr[i++] = nums2[r++];
        }
        return newArr;
    }


    // for test
    public static void main(String[] args) {
        int[] nums1 = {1},
                nums2 = {};
        double ans = findMedianSortedArrays(nums1, nums2);
        System.out.println(ans);
    }

}
